package com.bio.service.information.impl;

import java.io.Serializable;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.bio.dao.information.InformationDAO;
import com.bio.entity.attachemnt.Attachment;
import com.bio.entity.information.Information;
import com.bio.exception.OperationException;
import com.bio.service.attachment.AttachmentService;
import com.bio.service.impl.AbstractService;
import com.bio.service.information.InformationService;
import com.bio.utils.Environment;
import com.bio.utils.Pager;
import com.bio.utils.Pagination;

@Transactional
public class InformationServiceImpl extends AbstractService<Information, InformationDAO> implements InformationService{

	private AttachmentService attachmentService;
	

	public AttachmentService getAttachmentService() {
		return attachmentService;
	}

	public void setAttachmentService(AttachmentService attachmentService) {
		this.attachmentService = attachmentService;
	}

	public InformationServiceImpl(InformationDAO dao) {
		super(dao);
	}

	@Override
	public Pager<Information> findPagerByCompanyId(Pagination pagination,
			Long companyId) {
		return dao.findPagerByCompanyId(pagination, companyId);
	}

	@Override
	public Information save(Information information) throws OperationException {
		Long userId = Environment.Session.getUserId();
		String userName = Environment.Session.getUserName();
		Long companyId = Environment.Session.getCompanyId();
		List<Attachment> attachments = information.getAttachments();
		if(null != information){
			information.setPublisherId(userId);
			information.setPublisherName(userName);
			information.setCompanyId(companyId);
			
			String jsonString = attachmentService.batchProcess(attachments, information.getAttachmentsInfo(), information.getToDeletePics());
			information.setAttachmentsInfo(jsonString);
			information = super.save(information);
		}
		return information;
	}

	@Override
	public Information get(Serializable id) {
		Information info = super.get(id);
		if(null != info && StringUtils.isNotEmpty(info.getAttachmentsInfo())){
			JSONArray jArray = JSONArray.fromObject(info.getAttachmentsInfo());
			info.setAttachJSON(JSONArray.toList(jArray, JSONObject.class));
		}
		return info;
	}
}
